
package org.springblade.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.cache.SysCache;
import org.springblade.common.utils.IPUtils;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.dto.UserDto;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Date;

/**
 * 控制器
 *
 * @author Chill
 */
@RestController
@AllArgsConstructor
@RequestMapping("/password")
public class PasswordController {

    private final IUserService userService;

    private final IDeptService deptService;

    private final BladeRedis bladeRedis;


    //////重置
    @GetMapping("/resetPwd")
    public R resetPwd(String phone, String smscode, String password) {
        // 获取验证码
        String redisCode = bladeRedis.get(CacheNames.CAPTCHA_KEY_SMS + phone);
        // 判断验证码
        if (smscode == null || !StringUtil.equalsIgnoreCase(redisCode, smscode)) {
            return R.fail("验证码不正确");
        }

        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getTenantId, "000000").eq(User::getPhone, phone));
        if (StringUtils.isEmpty(user)) {
            return R.fail("手机号不存在");
        } else {
            User userUpPwd = new User();
            userUpPwd.setId(user.getId());
            userUpPwd.setPassword(DigestUtil.md5Hex(password));

            return R.status(userService.updateById(userUpPwd));
        }
    }

    /**
     * 注册
     */
    @PostMapping("/registerUser")
    public R registerUser(@RequestBody UserDto userDto) {

        String repeatKey = userDto.getPhone() + userDto.getSmscode() + userDto.getPassword();

        String value = bladeRedis.get(repeatKey);

        if (!StringUtils.isEmpty(value)) {
            return R.fail("点击过快请稍等");
        } else {
            bladeRedis.setEx(repeatKey, IPUtils.getUUIDString(), Duration.ofSeconds(2));
        }

        // 获取验证码
        String redisCode = bladeRedis.get(CacheNames.CAPTCHA_KEY_SMS + userDto.getPhone());
        // 判断验证码
        if (!redisCode.equals(userDto.getSmscode())) {
            return R.fail("验证码不正确");
        }

        userDto.setTenantId(BladeConstant.ADMIN_TENANT_ID);
        Tenant tenant = SysCache.getTenant(BladeConstant.ADMIN_TENANT_ID);


        Long userId = IdWorker.getId();
        userDto.setAccount(userDto.getPhone());
        userDto.setId(userId);
        userDto.setStatus(1);
        userDto.setIsDeleted(0);
        userDto.setAvatar("http://124.128.226.225:8083/upload/1301812392719626241.png");
        userDto.setName("志愿者" + userDto.getPhone());
        userDto.setRealName("志愿者" + userDto.getPhone());
        userDto.setUpdateUser(1123598821738675201L);
        userDto.setCreateUser(1123598817738675201L);
        userDto.setPostId("1123598821738675201");
        userDto.setCreateDept(1123598813738675201L);
        userDto.setCreateTime(new Date());
        userDto.setUpdateTime(new Date());
//        userDto.setRealName("");
        //TODO 后去直接根据角色code取
        userDto.setRoleId("1297054966580101122");
        //密码
        userDto.setPassword(DigestUtil.md5Hex(userDto.getPassword()));

        User userInsert = new User();
        BeanUtils.copyProperties(userDto, userInsert);
        userInsert.setUsertype("6");
        Integer userPhone = userService.count(Wrappers.<User>query().lambda().eq(User::getTenantId, BladeConstant.ADMIN_TENANT_ID).eq(User::getPhone, userInsert.getPhone()));
        if (userPhone > 0) {
            return R.fail("手机号已存在!" + userInsert.getPhone());
        }
        Integer userCount = userService.count(Wrappers.<User>query().lambda().eq(User::getTenantId, BladeConstant.ADMIN_TENANT_ID).eq(User::getAccount, userInsert.getAccount()));
        if (userCount > 0) {
            return R.fail("账户已存在!" + userInsert.getAccount());
        }
        boolean falg = userService.save(userInsert);
        //发送注册短信


        return R.status(falg);
    }


}
